<template>
  <div class="page grey-stage client-detail-page" style="overflow: hidden;" :style="{
    height: this.windowSize.height + 'px'
  }">
    <div class="client-detail-fixer" ref="fixerContainer">
      <div class="client-detail-content" ref="fixer">
        <custom-item
        v-if="init"
        :showMobile="true"
        :custom_id="custom_id"
        :value="this.client"
        :labels="stickedTags"
        v-model="client"
        :action="action"
        :isEditable="action !== 'search' && client.custom_property !== 'WX#' && client.custom_property !== 'NA#'"
        @input="back"
        >
          <div class="csi-item-right" slot="right" v-if="action !== 'search'">
            <!--<router-link v-if="action !=='search'" class="tag-link" :to="{path: 'stick-tag', query: {id: client.id, custom_type: custom_type, suid: client.suid}}">标签</router-link>-->
          </div>
        </custom-item>
      </div>
      <tab :line-width="1" ref="topTabbar">
        <tab-item
        :selected="navItem === item"
        v-for="(item, index) in navItems"
        @on-item-click="navItem = item"
        :key="index">{{item}}
       </tab-item>
      </tab>
    </div>
    <scrm-scroller
    v-show="this.navItem === '跟进记录'"
    class="normal-client-detail clearfix"
    ref="scroller"
    @refresh="refresh"
    :isHideFixer = "true"
    :more="hasClues"
    @hideFixer = "fixerCollapse = true"
    @showFixer = "fixerCollapse = false"
    :loading="loading"
    :topRefs="[this.$refs.fixerContainer]"
    :fixer="this.$refs.fixer"
    :bottomRefs="[this.$refs.tabbar]">
      <div class="timeline-wrap" ref="clueContainer">
        <div class="timeline" v-if="clues.length">
        <div v-for="(fulldata, index) in clueList" class="clearfix" :key="index">
          <clue-item :value="clientsDetail" :clueData="fulldata"></clue-item>
        </div>
        </div>
      </div>
      <div class="no-data-tip" v-if="!clues.length">该客户还没有跟进记录，赶紧去<router-link class="wrote-tip" :to="{path:'add-follow', query: {id:custom_id, custom_type:custom_type, suid:client.suid, type: 'GH#'}}">写跟进</router-link>哦~</div>
    </scrm-scroller>
    <sales-order
      v-show="this.navItem === '销售订单'"
      ref="salesScroller"
      class="normal-client-detail clearfix"
      @hideFixer = "fixerCollapse = true"
      @showFixer = "fixerCollapse = false"
      :topRefs="[this.$refs.fixerContainer]"
      :fixer="this.$refs.fixer"
      :bottomRefs="[this.$refs.tabbar]"
    />
    <div class="menu-wrapper" v-if="action !== 'search'">
        <client-menu
        ref="tabbar"
        @select-menu="menuItemSelected"
        :itemList="itemList"
        :client="client"
        @on-show="onMenuShow"
        @on-hide="onMenuHide"
        :custom_type="custom_type">
        </client-menu>

    </div>
    <div class="expander" @click="showHiddenFixer()">{{ fixerCollapse ? '展开' : '收起' }}</div>

    <x-dialog v-model="this.$store.state.app.dialogShow">
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>

    <popup v-model="show" @on-hide="handlePopup('hide')" @on-show="handlePopup('show')" height="100%" @touchstart.prevent style="background-color:white;">
      <div class="empty-btn-cell" @click="show = false"><span class="empty-btn btn">- 取消</span></div>
      <div class="dis-tip">您只能指派客户给自己团队的顾问</div>
      <div v-if="show === true" style="background-color:white;height:100%;">
        <div style="top:100px;" class="pdscroll" :class="{'none':!teamsMembers.length}" :on-infinite="loadMember" :on-refresh="refreshMember" ref="team_scroller" :noDataText="tnoDataText">
          <team-member-item @on-click="memberSelect" v-for="(teamMemberItem, index) in teamsMembers" :key="index" :client="teamMemberItem"></team-member-item>
        </div>
      </div>
    </popup>

    <popup
    v-model="teamShow"
    @on-hide="handlePopup('hide')"
    @on-show="handlePopup('show')"
    height="100%"
    style="background-color:white;">
      <div class="popup0" v-if="teamShow === true">
        <div v-if="teamShow === true" style="background-color:white;height:100%;"
          v-infinite-scroll="loadTeams"
          :infinite-scroll-disabled="teamLoading"
          infinite-scroll-distance="10"
        >
          <div :class="{'none':!teams.length}">
            <team-item @on-click="teamSelect"
              v-for="team in teams"
              :key="team.id" :teamName="team.team_name" :teamId="team.id"></team-item>
            <div v-if="teams.length && teamHasMoreData === true && teamLoading === false" class="view-more" @click="loadTeams">查看更多</div>
          </div>
          <div class="center-content-block" v-if="teamHasMoreData !== false && teamLoading !== false" style="padding-top:20px;">
            <mt-spinner type="snake"></mt-spinner>
          </div>
        </div>
      </div>
      <button class="fixed-bt-btn fixed-btr0-btn" v-if="teamShow === true" @click="teamShow=false">取消</button>
    </popup>

    <client-remind
    :clientId="custom_id"
    :isShow="remindShow"
    @on-cancel="onRemindCancel"
    @on-confirm="onRemindCancel"
    height="100%"
    style="background-color:white;" />


    <confirm v-model="auditionConfirm"
        title="温馨提示"
        @on-confirm="onAuditionConfirm">
      <p style="text-align:center;">你确定要约试听吗?</p>
    </confirm>
    <confirm v-model="sendCardConfirm"
        title="温馨提示"
        @on-confirm="onsendCardConfirm">
      <p style="text-align:center;">你确定要下发名片吗?</p>
    </confirm>
    <confirm v-model="backToClientSeasConfirm"
        title="温馨提示"
        @on-confirm="assignUserToClientSeas">
      <p style="text-align:center;">你确定要将此用户退回公海吗?</p>
    </confirm>
    <confirm v-model="disToTeamConfirm"
        title="温馨提示"
        @on-confirm="disToTeam">
      <p style="text-align:center;">你确定要将此用户指派给{{disTeamName}}?</p>
    </confirm>
    <confirm v-model="disToMemberConfirm"
        title="温馨提示"
        @on-confirm="disToMember">
      <p style="text-align:center;">你确定要将此用户指派给{{disMemberName}}?</p>
    </confirm>
  </div>
</template>

<script>
  const FOLLOW_RECORD = '跟进记录'
  const SALES_ORDER = '销售订单'
  const OTHER = '其它信息'

  // import Vue from 'vue'
  import clientMenu from '../components/client-menu'
  import ClientStatus from '../components/client-status'
  import ClueItem from '../components/clue-item'
  import clientProperties from '../components/client-properties'
  import {getCustomSource} from '../lib/client'
  import store from '../store'
  // import Scroller from 'vue-scroller'
  // import {XDialog, Popup} from 'vux'
  import XDialog from 'vux/src/components/x-dialog'
  import Popup from 'vux/src/components/popup'
  import Sticky from 'vux/src/components/sticky'
  import ScrmScroller from '../components/scrm-scroller'
  import { Tab, TabItem } from 'vux/src/components/tab'
  import teamMemberItem from '../components/team-member-item'
  import teamItem from '../components/team-item'
  import clientRemind from '../components/client-remind'
  import {showDialog, hideDialog} from '../lib/dialog'
  import { UPDATE_CLIENT_DETAIL } from '../store/mutation-types'
  import Confirm from 'vux/src/components/confirm'
  import Q from 'q'
  import { mapActions, mapState } from 'vuex'
  import zepto from 'npm-zepto'
  // 按需引入加载mint-ui更多插件
  import 'mint-ui/lib/loadmore/style.css'
  import 'mint-ui/lib/spinner/style.css'
  import 'mint-ui/lib/infinite-scroll/style.css'
  import {Loadmore, Spinner} from 'mint-ui'
  import customItem from '../components/custom-item'
  import salesOrder from './client-detail/sales-order'

  export default{
    props: {
    },
    data () {
      return {
        scroller: null,
        init: false,
        remindShow: false,
        fixerCollapse: false,
        hasClues: true,
        team_page_size: 20,
        team_page_index: 1,
        member_page_index: 1,
        navItems: [FOLLOW_RECORD, SALES_ORDER, OTHER],
        navItem: FOLLOW_RECORD,
        teamHasMoreData: true,
        teamLoading: false,
        teamShow: false,
        teams: [],
        disTeamName: '',
        disToTeamConfirm: false,
        disToTeam () {},
        disMemberName: '',
        disToMemberConfirm: false,
        disToMember () {},
        isShowHomeButton: true,
        action: '',
        imgServer: this.$store.state.app.imgServer,
        containerHeight: 'height: ' + document.body.scrollHeight + 'px;',
        itemList: [],
        collapse: true,
        custom_id: '',
        client: {},
        teamsMembers: [],
        noDataText: '',
        tnoDataText: '',
        scrollerTop: 0,
        stickedTags: [],
        scrollerHeight: '100%',
        babyList: [],
        auditionConfirm: false,
        sendCardConfirm: false,
        backToClientSeasConfirm: false,
        existsIds: [],
        page_size: 5,
        page_index: 1,
        custom_type: 0,
        team_page_index: 1,
        allClues: {},
        callable: true,
        clueList: {},
        show: false,
        clues: [],
        selectFollow: false,
        originNoDataText: '暂无跟进线索',
        allmessages: [],
        loading: false,
        clientsDetail: {},
        isChenJiao:false,
      }
    },
    methods: {
      ...mapActions({
        'findObjectTags': 'findObjectTags',
        'tagSign': 'tagSign',
        'getTeams': 'getTeams',
        'setIsShowHomeButton': 'setIsShowHomeButton',
      }),
      showHiddenFixer () {
        console.log('showFixer')
        if (this.fixerCollapse === true) {
          this.getScroller().showFixer()
        } else {
          this.getScroller().hideFixer()
        }
      },
      onRemindCancel () {
        this.remindShow = false
      },
      onMenuShow () {
        this.setIsShowHomeButton(false)
      },
      onMenuHide () {
        this.setIsShowHomeButton(true)
      },

      loadTeams (data) {
        return Q.promise((resolve, reject) => {
          let that = this
          let params = {
            page_index: this.team_page_index,
            page_size: this.team_page_size,
            status: encodeURIComponent('OK##')
          }
          if (this.teamLoading === true || this.teamHasMoreData === false) return
          this.teamLoading = true
          params = Object.assign(params, data)

          this.getTeams(params).then((response) => {
            const totalPage = Math.ceil(parseInt(response.data.results.total) / parseInt(this.team_page_size))
            this.teamHasMoreData = this.team_page_index < totalPage
            this.team_page_index++

            setTimeout(() => {
              this.teamLoading = false
              if (typeof response.data.results.teams !== 'undefined') {
                this.teams = this.teams.concat(response.data.results.teams || [])
                resolve(true)
              } else {
                console.warn('无团队')
              }
            })
          }).catch((e) => {
            this.teamLoading = false
            this.teamHasMoreData = false
          })
        })
      },
      initStickedTags () {
        return Q.Promise((resolve, reject) => {
          this.findObjectTags({ businessId: this.custom_id, tagObjectCode: this.tagObjectCode }).then((response) => {
            if (response.data.errcode === 0) {
              this.stickedTags = response.data.list
            }
            resolve()
          }).catch((err) => {
            resolve()
            console.log(err)
          })
        })
      },
      onAuditionConfirm () {
        this.sendH5()
      },
      onsendCardConfirm () {
        this.sendCard()
      },
      hideDialog: hideDialog,
      refresh (iscroll) {
        this.collapse = true
        this.getClues(false, false, true)
      },
      handleClick (clue) {
        if (this.custom_type === 1 && /主动添加一条预约/.test(clue.clue_desc) === true) {
          this.$router.push({ name: 'audtion', query: {clue_id: clue.id, id: this.custom_id} })
        } else if (clue.clue_type === 'YY#' && clue.clue_insert_type === 'YH#') {
          this.$router.push({ name: 'scan-code-detail', query: {clue_id: clue.id} })
        }
        // this.$router.push({ name: 'scan-code-detail', query: {clue_id: clue.id} })
      },
      initBabyInfo (id) {
        return Q.Promise((resolve, reject) => {
          store.dispatch('getBabys', id)
            .then((response) => {
              if (response.data.errcode === 0) {
                this.babyList = response.data.results
                resolve()
              } else {
                reject()
                console.log('服务器错误！请联系管理员!')
              }
            })
        })
      },
      handleDialog () {
      },
      log () {
        console.log('ee')
      },

      load (iscroll) {
        console.log('load')
        // Load new data
      },

      ininitBackToClientSeas () {
        let that = this
        let items = [
          {
            'id': 'refresh', // 字符串
            'text': '刷新'
          },
          {
            'id': 'backToClientSeas', // 字符串
            'text': '退回公海'
          },
          {
            'id': 'assign',
            'text': '转给顾问'
          },
          {
            'id': 'assignToTeam',
            'text': '转给团队'
          }
        ]

        // alert(this.loginUser.is_team_manager)

        // if (this.loginUser.is_team_manager === 1) {
        // }
        const dd = window['dd']
        // dd.biz.navigation.setMenu({
        //   backgroundColor: '#FFFFFF',
        //   textColor: '#0089cd',
        //   items: items,
        //   onSuccess: function (data) {
        //     console.debug(JSON.stringify(data))

        //     if (data.id === 'backToClientSeas') {
        //       that.backToClientSeasConfirm = true
        //       // that.assignUserToClientSeas()
        //     } else if (data.id === 'refresh') {
        //       that.$vux.loading.show({text: '加载中...'})
        //       location.reload()
        //     } else if (data.id === 'assign') {
        //       that.onItemClick(that.client.id)
        //     } else if (data.id === 'assignToTeam') {
        //       that.teamShow = true
        //     }
        //   /*
        //   {"id":"1"}
        //   */
        //   },
        //   onFail: function () {
        //   }
        // })
      },


      menuItemSelected (item) {
        console.log('item', item)
        const data = {id: item.to.path}
        if (item.to.path === 'h5-marketing') {
          this.auditionConfirm = true
        } else if (item.to.path === 'send-card') {
          this.sendCardConfirm = true
        } else if (data.id === 'backToClientSeas') {
          this.backToClientSeasConfirm = true
        } else if (data.id === 'assign') {
          this.onItemClick(this.client.id)
        } else if (data.id === 'assignToTeam') {
          this.teamShow = true
        } else if (data.id === 'remind') {
          this.remindShow = true
        }
      },

      initItemList (id) {
        let followPath = 'h5-marketing'
        let custom_type = this.custom_type
        let auditionLink = false
        if (custom_type === 1) {
          followPath = 'order-audition'
          auditionLink = true
        }

        this.itemList = [
          {
            title: '电话联系',
            to: { path: 'tel: ' + this.client.mobile_num }
          },
          {
            title: '写跟进',
            to: {path: 'add-follow', query: {id: this.custom_id, custom_type: this.custom_type, suid: this.client.suid}}
          },
          {
            title: '约试听',
            isLink: auditionLink,
            to: {path: followPath, query: {id: this.custom_id, custom_type: this.custom_type, suid: this.client.suid}}
          },
          {
            title: '发名片',
            isLink: false,
            isShow: custom_type === 0,
            to: {path: 'send-card', query: {id: this.custom_id, custom_type: this.custom_type, suid: this.client.suid}}
          },
          {
            title: '贴标签',
            to: {path: 'stick-tag', query: {id: this.custom_id, custom_type: this.custom_type, suid: this.client.suid}}
          }
        ]
      },
      getClues (data, isScroll, noneLoading) {
        data = Object.assign({
          page_size: this.page_size,
          custom_type: this.custom_type,
          page_index: this.page_index,
          own: '',
          custom_id: this.custom_id,
          order_by: 0
        }, data || {})

        let that = this
        if (this.loading === true) return
        this.loading = true
        if (data['page_index'] === 1 && noneLoading !== true) {
          this.$vux.loading.show({
            text: 'loading'
          })
        }

        store.dispatch('getClues', data).then((response) => {
          this.$vux.loading.hide()

          let data = response.data

          if (that.clues.length) {
            that.noDataText = ''
          }
          if (response.data.errcode === 0) {
            // this.$refs.scroller.scrollToTop()

            const result = response.data.results
            this.hasClues = Math.ceil(result.total / this.page_size)
              >=  this.page_index

            if (data.results.data.length) {
              let clues = data.results.data.concat(that.clues)

              clues.forEach((object, index) => {
                let insertDate = object.insert_time.split(' ')[0]
                if (this.existsIds.indexOf(object.id) === -1) {
                  this.existsIds.push(object.id)
                  if (typeof that.allClues[insertDate] === 'undefined') {
                    that.allClues[insertDate] = {'date': insertDate, 'clues': [object], 'day': insertDate}
                  } else {
                    that.allClues[insertDate].clues.push(object)
                  }
                }
              })

              let ascKeys = Object.keys(that.allClues).sort()
              let clueList = {}

              ascKeys.forEach((day, index) => {
                console.log(day, 'day')
                clueList[day] = {'date': day, clues: this.sortByKey(that.allClues[day].clues, 'insert_time')}
                // clueList[day] = {'date': day, clues: that.allClues[day].clues}
              })

              const time = that.page_index === 1 ? 0 : 1000
              that.page_index++

              // if (this.tid) {
              //   clearTimeout(this.tid)
              // }
              that.clueList = clueList
              that.clues = clues
              this.$nextTick(() => {
                this.endLoading()
              })
            } else {
              this.endLoading('', isScroll)
            }
          } else {
            this.endLoading('', isScroll)
            showDialog('系统服务异常！请联系管理员!')
          }

          this.$vux.loading.hide()
        }).catch((e) => {
          this.endLoading()
          this.$vux.loading.hide()
        })
      },
      sortByKey (array, key) {
        return array.sort(function (a, b) {
          var x = a[key]
          var y = b[key]
          return ((x < y) ? -1 : ((x > y) ? 1 : 0))
        })
      },
      endLoading (time, scrollToBottom) {
        let that = this
        if (this.etid) clearTimeout(this.etid)
        this.etid = setTimeout(() => {
          this.loading = false
          this.$nextTick(() => {
            if (!this.hasScrolled) {
              this.$refs.scroller.scrollToEnd()
              this.$nextTick(() => this.$refs.scroller.enableEvents())
              this.hasScrolled = true
            } else {
              this.$refs.scroller.scrollToTop()
              this.$nextTick(() => this.$refs.scroller.enableEvents())
            }
          })
        }, time || 100)
      },

      getCustomInfoById (id) {
        let that = this
        this.$vux.loading.show({text: 'loading'})

        store.dispatch('getCustomInfoById', id).then(function (response) {
          if (response.data.errcode === 0) {
            let client = response.data.results
            that.client = Object.assign(client, {baby_list: that.babyList})
            console.log(client.custom_property !== 'WX#', 'qunimalgb')

            let clientsDetail = Object.assign(that.clientsDetail, {[id]: that.client})
            store.commit(UPDATE_CLIENT_DETAIL, clientsDetail)
            console.log(that.$store.state.app)
            that.$nextTick(() => {
              that.init = true
            })
          } else {
            console.debug('系统服务异常！请联系管理员! ')
            showDialog(response.data.errmsg)
            setTimeout(() => {
              that.$router.back()
            }, 200)
          }
          that.$vux.loading.hide()
        }).catch((error) => {
          that.$vux.loading.hide()
          console.log(error)
        })
      },

      resizeScroll () {
        if (this.scid) clearTimeout(this.scid)
        // this.scid = setTimeout(() => {
        //   this.$refs.my_scroller.resize()
        // },200)
      },

      sendH5 () {
        let data = {
          custom_id: this.custom_id,
          h5_id: 1
        }
        if (this.lock === true) return
        this.lock = true

        this.$vux.loading.show({
          text: '约试听中...'
        })

        store.dispatch('sendH5', data).then((response) => {
          let msg = ''
          if (response.data.errcode === 0) {
            msg = '约试听成功！'
          } else {
            msg = response.data.errmsg
          }

          this.$vux.loading.hide()

          showDialog(msg)

          setTimeout(() => {
            hideDialog()
            this.getClues({page_index: 1}, true)
            this.lock = false
          }, 200)
        }).catch(() => {
          this.lock = false
        })
      },

      assignUserToOther () {
      },

      refreshMember (iscroll) {
        this.loadMembers()
        console.log('refreshMember')
        // Refresh current data
      },

      loadMember (iscroll) {
        console.log('loadMember')
        this.loadMembers()
        // Load new data
      },
      caculateScroller () {
        const clientDetailBody = this.$refs['fixerContainer']
        const winHeight = window.innerHeight
        this.scrollerTop = clientDetailBody.offsetHeight
        if (this.action !== 'search') {
          const tabbarHeight = this.$refs['tabbar'].offsetHeight
          this.scrollerHeight = winHeight - clientDetailBody.offsetHeight - tabbarHeight
        } else {
          this.scrollerHeight = winHeight - clientDetailBody.offsetHeight
        }

        this.resizeScroll()
      },
      onItemClick (clientID) {
        // this.teamsMembers = [];
        this.loadMembers()
        this.show = true
        this.selectedClientId = clientID
        console.log('clientID: ', clientID)
      },

      assignUserToClientSeas () {

        let info = {
          target_suid: '',
          custom_id: this.$route.query.custom_id,
          distribute_type: 'GH#',
          opt_type: 'BAC'
        };

        let that = this
        this.$vux.loading.show({text: 'loading'})

        store.dispatch('distribute', info).then((response) => {
          if (response.data.errcode === 0) {
            showDialog('客户已退回公海！')
            that.show = false
            setTimeout(() => {
              that.$router.replace({path: 'social-client', query: {custom_type:1}})
            }, 200)
          } else {
            showDialog(response.data.errmsg)
            console.log(JSON.stringify(response.data))
          }
          this.$vux.loading.hide()
        }).catch((error) => {
          showDialog('系统出错!')
          this.$vux.loading.hide()
          console.log(error)
        })
      },
      back () {
        if (this.client.custom_property === 'WX#' || this.client.custom_property === 'NA#') {
          this.$router.back()
        }
      },
      teamSelect (team) {
        let info = {
          team_id: team.team_id,
          custom_id: this.$route.query.custom_id,
          distribute_type: 'TP#',
          opt_type: 'TPT'
        }
        this.disMsg = '您将客户分配给团队：' + team.team_name
        return Q.Promise((resolve, reject) => {
          this.disTeamName = team.team_name
          this.disToTeamConfirm = true
          this.disToTeam = resolve
        }).then(() => {
          this.distribute(info)
        })
      },
      memberSelect(member) {
        let info = {
          target_suid:member.suid,
          custom_id: this.$route.query.custom_id,
          distribute_type: 'TP#',
          opt_type: 'TPT'
        }
        this.disMsg = '您将客户分配给成员：' + member.name
        return Q.Promise((resolve, reject) => {
          this.disMemberName = member.name
          this.disToMemberConfirm = true
          this.disToMember = resolve
        }).then(() => {
          this.distribute(info)
        })
      },

      distribute (info) {
        let that = this
        this.$vux.loading.show({text: 'loading'})

        store.dispatch('distribute', info).then((response) => {
          if (response.data.errcode === 0) {
            showDialog(this.disMsg)
            that.show = false
            setTimeout(() => {
              that.$router.replace({path: 'social-client', query: {custom_type: this.custom_type}})
              this.$vux.loading.hide()
            }, 200)
          } else {
            showDialog(response.data.errmsg)
            console.log(JSON.stringify(response.data))
            this.$vux.loading.hide()
          }

        }).catch((error) => {
          showDialog('系统出错!')
          this.$vux.loading.hide()
          console.log(error)
        });
      },

      loadMembers (data) {
        let that = this
        let params = {
          page_index: this.member_page_index,
          page_size: this.page_size,
          is_own: 1,
          source: 'webapp',
          team_id: this.client.team_id
        }
        params = Object.assign(params, data)
        store.dispatch('getTeams', params).then((response) => {
          setTimeout(() => {
            if (typeof response.data.results.teams !== 'undefined') {
              let teams = response.data.results.teams
              that.filterUserFromTeam(teams)
            } else {
              console.log(that.teamsMembers)
            }
            this.endTeamLoading()
            that.member_page_index++
          }, 200)
        }).catch((e) => {
          console.log(e)
          this.endTeamLoading()
        })
      },
      // 从接口中筛选出团队信息
      filterUserFromTeam (teams) {
        let temps = []
        if (!this.existTeamsIDs) this.existTeamsIDs = []
        let isSelfTeam = false

        teams.forEach((team, index) => {
          if (isSelfTeam === true) return
          team.team_managers.forEach((member, mindex) => {
            if (member.suid === this.loginUser.id) isSelfTeam = true
          })

          team.team_members.forEach((member, mindex) => {
            if (member.suid === this.loginUser.id) isSelfTeam = true
          })


          // if (true === isSelfTeam) {

            team.team_managers.forEach((member, mindex) => {
              let gid = member.suid
              if (this.existTeamsIDs.indexOf(gid) === -1)  {
                member.team_name = team.team_name
                temps.push(member)
                this.existTeamsIDs.push(gid)
              }

            })

            team.team_members.forEach((member, mindex) => {
              let gid = member.suid
              if (this.existTeamsIDs.indexOf(gid) === -1)  {
                member.team_name = team.team_name
                temps.push(member)
                this.existTeamsIDs.push(gid)
              }
            })

          // }
        })

        this.teamsMembers = this.teamsMembers.concat(temps)
      },
      endTeamLoading() {
        let that = this
        setTimeout(() =>{
          if (that.$refs.team_scroller) {
            that.$refs.team_scroller.finishInfinite(true)
            that.$refs.team_scroller.finishPullToRefresh()
            if (that.teamsMembers.length > 0) {
              that.tnoDataText = ''
            }
            // setTimeout(() => {
            //   if (this.$refs.team_scroller) {
            //     this.$refs.team_scroller.resize()
            //   }
            // },200)
          }
        }, 200)
      },

      handlePopup(status){
        console.log('222')
        // this.team_page_index = 1
        // this.existTeamsIDs = []

        if (status === 'show') {
          // setTimeout(() => {
          //   if (this.$refs.team_scroller) {
          //     this.$refs.team_scroller.resize()
          //   }
          // },200)
        } else {

        }
      },

      sendCard() {
        let data = {
          custom_id: this.custom_id
        }

        if (this.lock === true) return

        this.lock = true

        this.$vux.loading.show({
          text: '发名片中...'
        })

        store.dispatch('sendCard', data).then((response) => {
          let msg = ''

          if (response.data.errcode === 0) {
            msg = '发名片成功！'
          } else {
            msg = response.data.errmsg
          }

          this.$vux.loading.hide()

          showDialog(msg)

          setTimeout(() => {
            hideDialog()
            this.getClues({page_index: 1}, true)
            this.lock = false
          }, 200)
        }).catch(() => {
          this.lock = false
        })
      },

      saveClue () {
        // this.$router.back();
        this.$vux.loading.show({text: 'loading'})
        store.dispatch('saveClues', this.follow).then((response) => {
          if (response.data.errcode === 0) {
            showDialog('保存线索成功！')
            setTimeout(() => {
              this.$router.back()
            }, 200)
          } else {
            showDialog('系统出错!')
          }
          this.$vux.loading.hide()
        }).catch((e) => {
          this.$vux.loading.hide()
        })
      },
      getScroller () {
        const value = this.navItem
        if (value === FOLLOW_RECORD) {
          this.scroller = this.$refs.scroller
        } else if (value === SALES_ORDER) {
          this.scroller = this.$refs.salesScroller
          console.log('this.scroller', this.scroller)
        }
        return this.scroller
      }

    },
    components: {
      clientMenu,
      ClientStatus,
      clientProperties,
      XDialog,
      Popup,
      Confirm,
      teamMemberItem,
      teamItem,
      customItem,
      ClueItem,
      Tab,
      TabItem,
      Sticky,
      ScrmScroller,
      salesOrder,
      clientRemind,
      [Loadmore.name]: Loadmore,
      [Spinner.name]: Spinner
    },
    destroyed () {
      zepto('#app').removeClass('overflow-hidden')
      hideDialog()
    },
    mounted () {
      this.clientsDetail = this.defaultClientsDetail
      this.$vux.loading.show({
        text: 'Loading...'
      })
      this.scroller = this.getScroller()
      zepto('#app').addClass('overflow-hidden')
      let clientID = this.$route.query.custom_id
      this.action = this.$route.query.action
      this.isChenJiao = this.$route.query.isChenJiao
      console.debug('this.$route.query.custom_type', JSON.stringify(this.$route.query))

      this.noDataText = this.originNoDataText
      this.custom_id = clientID
      this.custom_type = parseInt(this.$route.query.custom_type)
      this.tagObjectCode = this.custom_type === 0 ? 'social_customer' : 'normal_customer'

      this.getCustomInfoById(clientID)
      this.initBabyInfo(clientID).then(() => {
        this.caculateScroller()
      })
      this.getClues(false, true)
      this.tagSign().then(this.initStickedTags)

      getCustomSource(store)

      this.callJsApi('biz.navigation.setTitle', {title: '客户详情'})

      if (this.$refs.my_scroller) {
        // let my_scroller = this.$refs.my_scroller
        // let height = this.$refs.my_scroller.$el.clientHeight
        // my_scroller.scrollTo(my_scroller.getPosition())
        this.resizeScroll()
      }

      // this.callable = this.$route.query.call && parseInt(this.$route.query.call) === 1
      this.callable = true
      // console.log(this.callable)

      // if (this.custom_type === 1) {
      if (this.action !== 'search') {
        this.ininitBackToClientSeas()
      }
      // }
    },

    watch: {
      navItem (value) {
        this.scroller = this.getScroller()
      },
      babyList () {
        console.log('babyList', this.babyList)
        this.client.baby_list = this.babyList
        this.client = this.client
        this.clientsDetail = Object.assign(this.clientsDetail, {[this.custom_id]: {baby_list: this.babyList}})
        store.commit(UPDATE_CLIENT_DETAIL, this.clientsDetail)
      },
      client () {
        this.initItemList()
      },

      clues () {
        // console.log(this.clues, 'allClues')
        this.resizeScroll()
      },

      loginUser () {
        // if (this.custom_type === 1) {
        this.ininitBackToClientSeas()
        // }
      },
      collapse () {
        setTimeout(() => {
          this.caculateScroller()
        })
      },
      windowSize (size) {
        this.caculateScroller()
      }

    },
    computed: {
      ddUser () {
        return this.$store.state.app.ddUser
      },
      loginUser () {
        return this.$store.state.app.user
      },
      ...mapState({
        windowSize: state => state.app.windowSize,
        defaultClientsDetail: state => state.app.clientsDetail
      })
    }
  }
</script>

<style >
  /*@import "../less/index.less";*/

  .gender-female,.gender-male {
  font-family: "Microsoft Yahei", 微软雅黑, arial, 宋体, sans-serif;
  font-weight: bolder;
}

.gender-female {
  color:#f75fb6;
}

.gender-male {
  color:#35adff;
}


</style>

<style lang="less">
  @import '../less/base.less';
  @import '../less/timeline.less';
  @import '../less/client-detail.less';

  .right .timeline-content .timeline-content-body {
    float:right;
    background-color:#BDE1FC;
    color:#666666;
  }

  .middle .timeline-content .timeline-content-body {
    background-color:#cccccc;
    color:rgba(255, 255, 255, 0.75);
  }

  .middle.timeline-block {
    max-width: 100%;
    margin-left: 0;
    margin-right: 0;

    .timeline-content {
        max-width: 200px;
        margin-left: auto;
        margin-right: auto;
    }
  }

  .csi-item-right {
    float: left;
  }

  .left .timeline-content .timeline-content-body {
    float: left;
    background-color: #fff;
    color: #666666;
  }



</style>
